package servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;

import biz.FoodBiz;
import biz.FoodTypeBiz;
import biz.impl.FoodBizImpl;
import biz.impl.FoodTypeBizImpl;
import entity.Food;
import entity.FoodType;
import servlet.util.FileSaveToDsk;
import servlet.util.FileUploadRequestParser;

@WebServlet("/admin/AdminFoodEditServlet.html")
public class AdminFoodEditServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String foodId = request.getParameter("foodId");
		int fId = Integer.valueOf(foodId);
		FoodBiz foodBiz = new FoodBizImpl();
		Food food = foodBiz.queryFoodByFoodId(fId);
		//food
		request.setAttribute("food", food);
		FoodTypeBiz foodTypeBiz= new FoodTypeBizImpl();
		List<FoodType> allFoodType = foodTypeBiz.queryAllFoodType();
		//foodType下拉框
		request.setAttribute("allFoodType", allFoodType);
		//foodTypeId of food
		int ftId = food.getFoodType().getFtId();
		request.setAttribute("ftId",ftId);
		//
		request.getRequestDispatcher("adminFoodEdit.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String foodId = request.getParameter("foodId");
		Integer fId = Integer.valueOf(foodId);
		//
		String foodName = request.getParameter("foodName");
		//
		String foodType = request.getParameter("foodType");
		Integer ftId = Integer.valueOf(foodType);
		FoodTypeBiz foodTypeBiz = new FoodTypeBizImpl();
		FoodType fType = foodTypeBiz.queryFoodTypeByFoodTypeId(ftId);
		//
		String foodPrice =request.getParameter("foodPrice");
		double fPrice = Double.valueOf(foodPrice);
		//
		String foodDesc = request.getParameter("foodDesc");
//		String imgPath = request.getParameter("imgPath");
		FileUploadRequestParser parser = new FileUploadRequestParser(request);
		FileItem fileFieId = parser.getFileFieId("imgPath");
		FileSaveToDsk fstd = new FileSaveToDsk(request);
		String clientName =fstd.getClientName();
		FoodBiz foodBiz = new FoodBizImpl();
		foodBiz.updateFood(new Food(fId,fType,foodName,foodDesc,clientName,fPrice));
		//修改成功
		response.sendRedirect("AdminFoodServlet");
	}

}
